package com.csii.activiti.server.core.utils;

import cn.hutool.core.collection.CollUtil;
import com.csii.activiti.server.core.constant.ActFlowStatusConstant;
import com.csii.activiti.server.core.constant.CommonConstant;
import com.csii.activiti.server.core.constant.FlowNodeTypeConstant;
import com.csii.activiti.server.core.entity.ActFlowProIdAndNode;
import com.csii.activiti.server.core.entity.GenericReferenceEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BasicCommonUtils {

    public static GenericReferenceEntity<List<ActFlowProIdAndNode>, Map<String,Boolean>> queryFlowProIdAndNodeGetGroupMaxAndWithdraw(List<ActFlowProIdAndNode> proIdAndNodeList){
        if (CollUtil.isNotEmpty(proIdAndNodeList)){
            proIdAndNodeList = proIdAndNodeList.stream().filter(item-> !(item.getActId().startsWith(FlowNodeTypeConstant.URGING_NODE) || item.getActId().equals(CommonConstant.URGING_SERVICE_NODE_ID))).collect(Collectors.toList());
            List<ActFlowProIdAndNode> dataList = new ArrayList<>();
            Map<String,Boolean> processInstanceIdAndWithdraw = new HashMap<>();
            String lastProcessInstanceId = null;
            String lastActId = null;
            int count = 1;
            for (ActFlowProIdAndNode actFlowProIdAndNode : proIdAndNodeList) {

                if (lastProcessInstanceId == null){
                    lastProcessInstanceId = actFlowProIdAndNode.getProcessInstanceId();
                    lastActId = actFlowProIdAndNode.getActId();
                }
                if (lastProcessInstanceId.equals(actFlowProIdAndNode.getProcessInstanceId())){
                    if (lastActId.equals(actFlowProIdAndNode.getActId())){
                        dataList.add(actFlowProIdAndNode);
                    }else{
                        count++;
                    }
                }else{
                    count = 1;
                    lastProcessInstanceId = actFlowProIdAndNode.getProcessInstanceId();
                    lastActId = actFlowProIdAndNode.getActId();
                    dataList.add(actFlowProIdAndNode);
                }
                if (count >2 || actFlowProIdAndNode.getDeleteReason() != null){
                    processInstanceIdAndWithdraw.put(lastProcessInstanceId,false);
                }

            }
            return new GenericReferenceEntity<>(dataList,processInstanceIdAndWithdraw);
        }
        return new GenericReferenceEntity<>(new ArrayList<>(),new HashMap<>());
    }
}
